package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/4/24 14:16
 * Version:1.0-SNAPSHOT
 * Description:
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            Map<String,FileItem> items = new HashMap<>();
            for(FileItem fileItem : fileItems){
                items.put(fileItem.getFieldName(),fileItem);
            }
            String path = getServletContext().getRealPath("/upload/"+new SimpleDateFormat("yyyyMMdd").format(new Date()));
            File f = new File(path);
            f.mkdirs();
            FileItem file = items.get("file");
            String username = items.get("username").getString("UTF-8");
            System.out.println("用户名:"+username);
            file.write(new File(path,file.getName()));
            out.print("success");
        } catch (Exception e) {
            e.printStackTrace();
            out.print("fail");
        }
    }

}
